package com.qcby.controller;


import com.qcby.entity.Query.ShopQuery;
import com.qcby.entity.Result;
import com.qcby.entity.Shop;
import com.qcby.entity.Tag;
import com.qcby.service.ShopService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/homepage")
public class HomePageController {
    @Autowired
    private ShopService shopService;
/*    @ResponseBody
    @PostMapping("/findAll")
    public Result<List<ShopQuery>> findAll(ShopQuery shop){
        List<ShopQuery> shops = shopService.findAll(shop);
        for (Shop s : shops) {
            Integer shopId = s.getId();
            Double averageRating = shopService.getRecent100RatingsAverage(shopId).getData();
            s.setRating(averageRating != null ? averageRating : 0.0);
        }
        return Result.success(shops);
    }*/
@ResponseBody
@PostMapping("/findAll")
public Result<Map<String, Object>> findAll(ShopQuery query) {
    // 1. 分页参数默认值（避免null导致的SQL错误）
    if (query.getPage() == null || query.getPage() < 1) {
        query.setPage(1);
    }
    if (query.getPageSize() == null || query.getPageSize() < 1) {
        query.setPageSize(6);  // 与前端pageSize保持一致
    }

    // 2. 计算分页起始位置（MySQL的LIMIT起始索引从0开始）
    int start = (query.getPage() - 1) * query.getPageSize();

    // 3. 查询当前页数据（带筛选条件）
    List<Shop> shops = shopService.findByPage(query, start, query.getPageSize());

    // 4. 计算评分（保持原有逻辑）
    for (Shop shop : shops) {
        Double avgRating = shopService.getRecent100RatingsAverage(shop.getId()).getData();
        shop.setRating(avgRating != null ? avgRating : 0.0);
    }

    // 5. 查询总条数（基于当前筛选条件）
    int total = shopService.countByQuery(query);

    // 6. 封装结果返回给前端
    Map<String, Object> result = new HashMap<>();
    result.put("list", shops);
    result.put("total", total);
    return Result.success(result);
}
    @ResponseBody
    @PostMapping("/selectShopByTag")
    public Result<List<Shop>> selectShopByTag(String tagName){
        List<Shop> shops = shopService.selectShopByTag(tagName);
        return Result.success(shops);
    }
    @ResponseBody
    @PostMapping("/findTags")
    public Result<List<Tag>> findTags(){
        List<Tag> tags = shopService.findTags();
        return Result.success(tags);
    }
    @GetMapping("/goToDetail")
    public String goToDetail(Integer id, Model model){
        model.addAttribute("shopId",id);
        Shop shop = shopService.goToDetail(id);
        //List<Review> reviews=shopService.getReviewsByShopId(id);
        model.addAttribute("shop",shop);
        //model.addAttribute("reviews",reviews);
        return "shop_detail";
    }
    @ResponseBody
    @PostMapping("/like")
    public Result<Integer> like(Integer targetId,Integer userId){
        return shopService.like(targetId,userId);
    }
    @ResponseBody
    @PostMapping("/likeStatus")
    public Result<Integer> likeStatus(Integer targetId,Integer userId){
        return shopService.likeStatus(targetId,userId);
    }

    @ResponseBody
    @PostMapping("/likeCount")
    public Result<Integer> likeCount(@Param("targetId") Integer targetId, @Param("target_type")String target_type){
        return shopService.likeCount(targetId,target_type);
    }
    @ResponseBody
    @PostMapping("/likeToggle")
    public Result<Integer> likeToggle(@Param("targetId") Integer targetId,
                                      @Param("userId") Integer userId,
                                      @Param("target_type")String target_type){
        int status = shopService.likeStatus(targetId,userId).getData();
        if (status==1){
            int d = shopService.likeDelete(targetId,userId,target_type).getData();
            if (d>0)
            return Result.success(0);
            else
                return Result.error("取消点赞失败");
        }else {
            int d = shopService.like(targetId,userId).getData();
            if (d>0)
                return Result.success(1);
            else
                return Result.error("点赞失败");
        }
    }


}
